package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.DropOffBikeBean;
import com.ekuaitu.kuaitu.bean.HeartBean;
import com.ekuaitu.kuaitu.bean.OrderDetailBean;
import com.ekuaitu.kuaitu.bean.QueryLockBean;
import com.ekuaitu.kuaitu.bean.ResultBean;
import com.ekuaitu.kuaitu.bean.UnFinishOrderBean;
import com.ekuaitu.kuaitu.ble.BluetoothHelper;
import com.ekuaitu.kuaitu.ble.ClientManager;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.NetUtils;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BikeInUseActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.bike_inUse_tvHotline)
    TextView bikeInUseTvHotline;
    @BindView(R.id.toolbar_bike_inUse)
    Toolbar toolbarBikeInUse;
    @BindView(R.id.bike_inuse_tvStart)
    TextView bikeInuseTvStart;
    @BindView(R.id.bike_inuse_tvNum)
    TextView bikeInuseTvNum;
    @BindView(R.id.time_carbon)
    AutoLinearLayout timeCarbon;
    @BindView(R.id.bike_inuse_tvDuration)
    TextView bikeInuseTvDuration;
    @BindView(R.id.bike_inuse_tvReturn)
    TextView bikeInuseTvReturn;
    @BindView(R.id.bike_inuse_llrepair)
    AutoLinearLayout bikeInuseLlrepair;
    @BindView(R.id.bike_inuse_llScan)
    AutoLinearLayout bikeInuseLlScan;
    @BindView(R.id.progressBar_bike_inUse_pro)
    ProgressBar progressBarBikeInUsePro;
    @BindView(R.id.progressBar_bike_inUse)
    AutoRelativeLayout progressBarBikeInUse;
    @BindView(R.id.activity_bike_in_use)
    AutoRelativeLayout activityBikeInUse;
    private ProgressDialog pdSearch;
    //private ProgressDialog pdConnect;
    private Context mContext = this;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private long count = 0;
    private String orderId;
    private String bikeId;
    private int lockType;
    private boolean isExit = false;
    private String bikeLicense;
    private TimerTask task;
    private Timer timer;
    private PowerManager.WakeLock wakeLock;
    public static LatLng curPosition = new LatLng(0, 0);
    public static AMapLocation aMapLocation;
    private int power;
    private int caozuo = -1;
    private int type;
    private KuaituDialog kuaituDialog;
    byte[] btToken = new byte[4];
    byte[] loadPwd = new byte[6];
    byte[] loadKey = new byte[16];
    /* byte[] loadKey = {32, 87, 47, 82, 54, 75, 63, 71, 48, 80, 65, 88, 17, 99, 45, 43};
     byte[] loadPwd = {0x30, 0x30, 0x30, 0x30, 0x30, 0x30};*/
    private String btMac;
    private long heatCount;
    private boolean isSendHeat;
    private CountDownTimer searchTimer;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bike_in_use;
    }

    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        orderId = intent.getStringExtra(IntentKey.INTENT_ORDER_ID);
        btMac = intent.getStringExtra("btMac");
        lockType = intent.getIntExtra(IntentKey.INTENT_LOCK_TYPE, -1);
        pdSearch = new ProgressDialog(BikeInUseActivity.this);
        MobclickAgent.onEvent(this, Constants.RIDINGVCAPPEAR);
    }


    private void getBikeType() {
        progressBarBikeInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).requestBTBikeInfo(MyApplication.getInstance().getRequestFieldMap(), bikeId, "0")
                .enqueue(new Callback<QueryLockBean>() {
                    @Override
                    public void onResponse(Call<QueryLockBean> call, final Response<QueryLockBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            progressBarBikeInUse.setVisibility(View.GONE);
                            if (response.body().getStatus() == 200) {
                                btMac = response.body().getAttachment().getBikeMachineUnique();
                                lockType = response.body().getAttachment().getLockType();
                                if (lockType == 2 || lockType == 3 || lockType == 4) {
                                    String key = response.body().getAttachment().getBikeMachineKey();
                                    String pwd = response.body().getAttachment().getBikeMachinePassword();
                                    String[] KEY = key.split(",");
                                    String[] PWD = pwd.split(",");
                                    for (int i = 0; i < 16; i++) {
                                        loadKey[i] = Byte.parseByte(KEY[i]);
                                    }
                                    for (int j = 0; j < 6; j++) {
                                        loadPwd[j] = Byte.parseByte(PWD[j]);
                                    }
                                    progressBarBikeInUse.setVisibility(View.VISIBLE);
                                    ClientManager.getClient().registerBluetoothStateListener(mBluetoothStateListener);
                                    if (ClientManager.getClient().isBluetoothOpened()) {
                                        int status = ClientManager.getClient().getConnectStatus(btMac);
                                        if (status == 2) {
//                                            preLockPower = true;
//                                            byte[] lockPower = {0x02, 0x01, 0x01, 0x01, btToken[0], btToken[1], btToken[2], btToken[3], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//                                            sendData(lockPower, btMac);
                                            BluetoothHelper.getInstance().loadLockData(btMac, MyApplication.btToken, loadPwd, loadKey);
                                            BluetoothHelper.getInstance().setBluetoothCommandCallback(commandCallback);//蓝牙指令回调
                                            progressBarBikeInUse.setVisibility(View.GONE);
                                            //查询电量
                                            BluetoothHelper.getInstance().checkDianLiang();
                                        } else {
                                            Log.i("saomiao", "未连接" + status);
                                            BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                                        }
                                    } else {
                                        ClientManager.getClient().openBluetooth();
                                    }

                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            progressBarBikeInUse.setVisibility(View.GONE);
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<QueryLockBean> call, Throwable t) {
                        progressBarBikeInUse.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //还蓝牙单车
    private void dropOffBTBike(String power, final String mac, String errorCode) {
        commitBikeLogPre();
        progressBarBikeInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).dropOffBike(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId, curPosition.longitude + "",
                curPosition.latitude + "", lockType + "", power, errorCode)
                .enqueue(new Callback<DropOffBikeBean>() {
                    @Override
                    public void onResponse(Call<DropOffBikeBean> call, final Response<DropOffBikeBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            progressBarBikeInUse.setVisibility(View.GONE);
                            if (response.body().getStatus() == 200) {
                                ClientManager.getClient().disconnect(mac);
                                if (response.body().getAttachment().getIsprize().equals("2")) {  //报修免单
                                    final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseActivity.this);
                                    kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                    kuaituDialog.setMessage("此次骑行将不收取费用。");
                                    kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                                        @Override
                                        public void onYesClick() {
                                            kuaituDialog.dismiss();
                                            startActivity(new Intent(mContext, MainActivity.class));
                                            finish();
                                        }
                                    });
                                    kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            kuaituDialog.dismiss();
                                            finish();
                                        }
                                    });
                                    kuaituDialog.setCancelable(false);
                                    kuaituDialog.show();
                                } else {
                                    IntentUtils.toSettlementActivity(BikeInUseActivity.this, orderId, bikeId);
                                    finish();
                                }
                                commitBikeLogSuccess();
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                                commitBikeLogFailed(response.body().getStatus(), response.body().getMessage());
                            }
                        } else {
                            progressBarBikeInUse.setVisibility(View.GONE);
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).show();
                            commitBikeLogFailed(404, "服务器异常");
                        }
                    }

                    @Override
                    public void onFailure(Call<DropOffBikeBean> call, Throwable t) {
                        progressBarBikeInUse.setVisibility(View.GONE);
                        Log.i("netError", "Inuse001" + t);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //蓝牙打开结果
    private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            if (isForeground(BikeInUseActivity.this, "com.ekuaitu.kuaitu.activity.BikeInUseActivity")) {
                if (openOrClosed) {
                    BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                } else {
                    progressBarBikeInUse.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, "蓝牙未开启", Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    //判断页面是否在前台
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    //蓝牙设备搜索结果
    private final SearchResponse mSearchResponse = new SearchResponse() {
        @Override
        public void onSearchStarted() {
            //progressBarBikeInUse.setVisibility(View.VISIBLE);
            progressBarBikeInUse.setGravity(View.GONE);
            pdSearch.setMessage("正在联系单车...");
            pdSearch.setCancelable(false);
            pdSearch.show();
            //调用show方法显示进度条对话框
            //使用匿名内部类实现线程并启动
            //对话框提示语，10秒后改变提示语
            searchTimer = new CountDownTimer(20000, 1000) {
                @Override
                public void onTick(long l) {
                    if (l >= 10000) {
                        handler.sendEmptyMessage(0);  //更新progress的提示语
                    } else {
                        handler.sendEmptyMessage(2);  //更新progress的提示语
                    }
                }

                @Override
                public void onFinish() {
                    handler.sendEmptyMessage(3);  //dismiss progress
                }
            };
            searchTimer.start();
        }

        @Override
        public void onDeviceFounded(SearchResult device) {
            if (device.scanRecord[5] == 0x01 && device.scanRecord[6] == 0x02) {
                if (device.getAddress().equals(btMac)) {
                    ClientManager.getClient().stopSearch();
                    power = device.scanRecord[14];
                    MyApplication.power = power;
            /*        searchTimer.cancel();
                    searchTimer = null;*/
                    //connectDevice(btMac);
                    BluetoothHelper.getInstance().connectDevice(btMac, loadPwd, loadKey, new BluetoothHelper.OnConnectListener() {
                        @Override
                        public void onConnectSuccess() {
                            ClientManager.getClient().stopSearch();
                            searchTimer.cancel();
                            searchTimer = null;
                        }

                        @Override
                        public void onConnectFailed() {
                            Toast.makeText(BikeInUseActivity.this, "连接设备失败", Toast.LENGTH_SHORT).show();
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            handler.sendEmptyMessage(3);  //dismiss progress
                            commitBikeLogFailed(0, "inUse连接失败");
                        }
                    });
                }
            }
        }

        @Override
        public void onSearchStopped() {
            commitBikeLogFailed(0, "未扫描到该单车，请将手机靠近车锁再试");
            //未搜索到蓝牙
            progressBarBikeInUse.setVisibility(View.GONE);
            handler.sendEmptyMessage(3);  //dismiss progress
         /*   searchTimer.cancel();
            searchTimer = null;*/
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            if (caozuo == 0) {
                caozuo = -1;
                dropOffBTBike("", btMac, "1");
            }
        }

        @Override
        public void onSearchCanceled() {
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            //搜索到后执行此方法，此时已经发起连接
            progressBarBikeInUse.setVisibility(View.GONE);
        }
    };

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        kuaituDialog = new KuaituDialog(BikeInUseActivity.this);
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mLocationClient.setLocationListener(this);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        startLocation();
    }

    //心跳计时
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    count++;
                    bikeInuseTvDuration.setText(TimeUtils.formatSecondCount(count + "", 1));
                    //app进入前台发送心跳
                    if (isSendHeat && heatCount % 600 == 0) {
                        commitBikeLogHeatPre();
                        sendHeat();
                    }
                    heatCount++;
                    break;
                case 2:
                    if (pdSearch != null) {
                        pdSearch.setMessage("正在联系单车，请耐心等待...");
                    }
                    break;
                case 3:
                    if (pdSearch != null) {
                        pdSearch.dismiss();
                    }
                    if (searchTimer != null) {
                        searchTimer.cancel();
                        searchTimer = null;
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void sendHeat() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL_PHP).sendHeart(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId, "0.1", "0.1", lockType + "", "0").enqueue(new Callback<HeartBean>() {
            @Override
            public void onResponse(Call<HeartBean> call, Response<HeartBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrorCode() == 0) {
                        Log.i("heart", "heart");
                        commitBikeLogHeatSuccess();
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMsg(), Toast.LENGTH_LONG).show();
                        commitBikeLogHeatFailed(response.body().getErrorCode(), response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<HeartBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }

    //开始定位
    private void startLocation() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                mLocationClient.startLocation();
            }
        } else {
            mLocationClient.startLocation();
        }
    }

    //定位动态权限申请允许后
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mLocationClient.startLocation();
            } else if (grantResults.length == 1 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("您已拒绝定位权限");
                kuaituDialog.setYesOnclickListener("开启", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                        startLocation();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        progressBarBikeInUse.setVisibility(View.GONE);
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setCancelable(false);
                kuaituDialog.show();

            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
        //相机权限允许后
        if (requestCode == Constants.READ_CAMERA_PERMISSION_REQUEST) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                intentScanBike();
            } else if (grantResults.length == 1 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("您已拒绝相机权限");
                kuaituDialog.setYesOnclickListener("开启", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        getCameraPermission();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setCancelable(false);
                kuaituDialog.show();
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }


    private void getOrderDetail(String orderId) {
        progressBarBikeInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getOrderDetail(MyApplication.getInstance().getRequestFieldMap(), orderId)
                .enqueue(new Callback<OrderDetailBean>() {
                    @Override
                    public void onResponse(Call<OrderDetailBean> call, Response<OrderDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            progressBarBikeInUse.setVisibility(View.GONE);
                            if (response.body().getStatus() == 200) {
                                OrderDetailBean.AttachmentBean result = response.body().getAttachment();
                                bikeLicense = result.getBikeModel().getLicenseTag();
                                bikeInuseTvNum.setText(bikeLicense);
                                bikeInuseTvStart.setText(TimeUtils.getFormatDate(result.getStartBillingTime() + "", "HH:mm:ss"));
                                bikeId = result.getBikeModel().getId();
                                Date date = new Date();
                                if (result.getStartBillingTime() <= 0) {
                                    count = 1;
                                } else {
                                    count = (int) ((date.getTime() - result.getStartBillingTime()) / 1000) + 1;
                                }
                                if (count < 0) {
                                    count = 1;
                                }
                                bikeInuseTvDuration.setText(TimeUtils.formatSecondCount(count + "", 1));
                                countTime();
                                getBikeType();
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<OrderDetailBean> call, Throwable t) {
                        progressBarBikeInUse.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //开锁进度框计时器
    private void countTime() {
        if (task == null) {
            task = new TimerTask() {
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendEmptyMessage(1);
                }
            };
        }
        if (timer == null) {
            timer = new Timer(true);
            timer.schedule(task, 0, 1000); //延时0ms后执行，1000ms执行一次
        }
        acquireWakeLock();
    }


    private void getUnFinishOrder() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUnFinishOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<UnFinishOrderBean>() {
                    @Override
                    public void onResponse(Call<UnFinishOrderBean> call, final Response<UnFinishOrderBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                progressBarBikeInUse.setVisibility(View.GONE);
                                if (response.body().getAttachment().getIsUnfinished() != 0) {
                                    if (response.body().getAttachment().getStatus() == 15) {
                                        orderId = response.body().getAttachment().getOrderId();
                                        bikeId = response.body().getAttachment().getOrderModel().getBikeModel().getBikeId();
                                        final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseActivity.this);
                                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                        kuaituDialog.setMessage("您已还车，请去结算");
                                        kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesClick() {
                                                IntentUtils.toSettlementActivity(BikeInUseActivity.this, orderId, bikeId);
                                                finish();
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                            @Override
                                            public void onNoClick() {
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setCancelable(false);
                                        kuaituDialog.show();
                                    } else if (response.body().getAttachment().getStatus() == 10) {
                                        getCameraPermission();
                                    } else {
                                        Intent intent = new Intent(mContext, MainActivity.class);
                                        intent.putExtra("isLogin", true);
                                        startActivity(intent);
                                        finish();
                                    }
                                } else {  //没有未完成订单
                                    Intent intent = new Intent(mContext, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<UnFinishOrderBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                    }
                });
    }

    //跳转扫码页面
    private void intentScanBike() {
        Intent intent = new Intent(mContext, ScanBikeQrActivity.class);
        intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
        intent.putExtra(IntentKey.INTENT_BIKE_LICENSE_DESIGNATED, bikeLicense);
        intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
        intent.putExtra("requestCode", Constants.REQUEST_SCAN_INUSE);
        startActivity(intent);
    }

    private boolean isFirstLocation = true;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            isFirstLocation = false;
            this.aMapLocation = aMapLocation;
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        } else if (isFirstLocation) {
            ToastCompat.makeText(mContext, "获取位置信息失败...", Toast.LENGTH_LONG).show();
        }
    }

    //还车GPS单车
    private void dropOffBike(String longitude, String latitude) {
        commitBikeLogPre();
        progressBarBikeInUse.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).dropOffBike(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId, longitude,
                latitude, lockType + "", "", "0").enqueue(new Callback<DropOffBikeBean>() {
            @Override
            public void onResponse(Call<DropOffBikeBean> call, Response<DropOffBikeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getIsprize().equals("2")) {  //报修免单
                            final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseActivity.this);
                            kuaituDialog.setTitle(getString(R.string.dialogTitle));
                            kuaituDialog.setMessage("此次骑行将不收取费用。");
                            kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    kuaituDialog.dismiss();
                                    startActivity(new Intent(mContext, MainActivity.class));
                                    finish();
                                }
                            });
                            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    kuaituDialog.dismiss();
                                    finish();
                                }
                            });
                            kuaituDialog.setCancelable(false);
                            kuaituDialog.show();
                        } else {
                            IntentUtils.toSettlementActivity(BikeInUseActivity.this, orderId, bikeId);
                            finish();
                        }
                        commitBikeLogSuccess();
                    } else if (response.body().getStatus() == 404) {
                        ToastCompat.makeText(mContext, "您距离单车太远", Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(404, "您距离单车太远");
                    } else if (response.body().getStatus() == 403) {
                        ToastCompat.makeText(mContext, "与单车通信失败", Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(403, "与单车通信失败");
                    } else if (response.body().getStatus() == 400) {
                        ToastCompat.makeText(mContext, "还车失败", Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(400, "还车失败");
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(response.body().getStatus(), response.body().getMessage());
                    }
                }
                progressBarBikeInUse.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<DropOffBikeBean> call, Throwable t) {
                progressBarBikeInUse.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }


    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastCompat.makeText(this, "订单进行中，再按一次退出应用", Toast.LENGTH_LONG).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 3000);
        } else {
            releaseWakeLock();
            AppManager.getAppManager().AppExit(mContext);
        }
    }

    //开启设备电源锁
    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }


    }

    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    private void getCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constants.READ_CAMERA_PERMISSION_REQUEST);
            } else {
                intentScanBike();
            }
        } else {
            intentScanBike();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isSendHeat = false;
        heatCount = 0;
        if (!TextUtils.isEmpty(btMac)) {
            BluetoothHelper.getInstance().resetNotifyCallback(btMac);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        heatCount = 0;
        isSendHeat = true;
        getOrderDetail(orderId);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (btMac != null) {
            ClientManager.getClient().disconnect(btMac);
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (task != null) {
            task.cancel();
            task = null;
        }

        if (searchTimer != null) {
            searchTimer.cancel();
            searchTimer = null;
        }
    }


    //bike-APP端操作日志记录 操作前
    private void commitBikeLogPre() {
        NetUtils.commitBikeLog(BikeInUseActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "6", "1", "0", "", "");
    }

    //bike-APP端操作日志记录 操作成功
    private void commitBikeLogSuccess() {
        NetUtils.commitBikeLog(BikeInUseActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "6", "2", "0", "200", "");
    }

    //bike-APP端操作日志记录 操失败
    private void commitBikeLogFailed(int errorcode, String errormsg) {
        NetUtils.commitBikeLog(BikeInUseActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "6", "3", "4", errorcode + "", errormsg);
    }

    //bike-APP端操作日志记录 操作前 心跳
    private void commitBikeLogHeatPre() {
        NetUtils.commitBikeLog(BikeInUseActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "7", "1", "0", "", "");
    }

    //bike-APP端操作日志记录 操作成功 心跳
    private void commitBikeLogHeatSuccess() {
        NetUtils.commitBikeLog(BikeInUseActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "7", "2", "0", "200", "");
    }

    //bike-APP端操作日志记录 操失败 心跳
    private void commitBikeLogHeatFailed(int errorcode, String errormsg) {
        NetUtils.commitBikeLog(BikeInUseActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "7", "3", "4", errorcode + "", errormsg);
    }


    @OnClick({R.id.bike_inUse_tvHotline, R.id.bike_inuse_tvReturn, R.id.bike_inuse_llrepair, R.id.bike_inuse_llScan})
    public void onClick(View view) {
        switch (view.getId()) {
            //客服电话
            case R.id.bike_inUse_tvHotline:
                final Intent intent2 = new Intent();
                intent2.setClass(mContext, ComplaintsActivity.class);
                intent2.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                intent2.putExtra(IntentKey.INTENT_TRIP_MODE, 2);
                intent2.putExtra("licenseTag", bikeLicense);
                startActivity(intent2);
                break;
            //还车
            case R.id.bike_inuse_tvReturn:
                if (lockType == 2 || lockType == 3 || lockType == 4) {
                    if (SharedPreferencesUtils.getInstance(mContext).getBooleanValue(Constants.LOCK_IS_CLOSE)) {
                        dropOffBTBike(power + "", btMac, "0");
                    } else {
                        initGps();
                    }
                } else {
                    initGps();
                }

                MobclickAgent.onEvent(this, Constants.RETURN_BIKE);
                break;
            //单车修复
            case R.id.bike_inuse_llrepair:
                Intent intent = new Intent(mContext, RepairBTBikeActivity.class);
                intent.putExtra("bikeLicense", bikeLicense);
                intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
                intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                if (lockType == 2 || lockType == 3 || lockType == 4) {
                    intent.putExtra("mac", btMac);
                }
                intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
                startActivity(intent);
                break;
            //开锁
            case R.id.bike_inuse_llScan:
                getUnFinishOrder();
                MobclickAgent.onEvent(BikeInUseActivity.this, Constants.RIDINGOPENLOCK);
                break;
        }
    }

    private void initGps() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断定位服务是否开启，如果没有则开启
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            progressBarBikeInUse.setVisibility(View.VISIBLE);
            caozuo = 0;
            if (curPosition.latitude != 0 && curPosition.longitude != 0) {
                if (lockType == 1) {
                    dropOffBike(curPosition.longitude + "", curPosition.latitude + "");
                } else if (lockType == 2 || lockType == 3 || lockType == 4) {
                    if (ClientManager.getClient().isBluetoothOpened()) {
                        int status = ClientManager.getClient().getConnectStatus(btMac);
                        Log.i("还车连接状态", status + "");
                        //如果蓝牙已经连接，直接发送数据；未连接则开始搜索蓝牙。
                        if (ClientManager.getClient().getConnectStatus(btMac) == 2) {
                            btToken = MyApplication.btToken;
                            BluetoothHelper.getInstance().checkStatus();
                        } else {
                            BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                        }

                    } else {
                        ClientManager.getClient().openBluetooth();
                    }
                }
            } else {
                ToastCompat.makeText(mContext, "正在获取您的位置信息", Toast.LENGTH_LONG).show();
            }
        } else {
            final KuaituDialog kuaituDialog = new KuaituDialog(this);
            kuaituDialog.setTitle(getString(R.string.dialogTitle));
            kuaituDialog.setMessage(getString(R.string.OpenGpsReminder));
            kuaituDialog.setSingleButton(true);
            kuaituDialog.setYesOnclickListener("去设置", new KuaituDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, Constants.REQUEST_Location_Service);
                    kuaituDialog.dismiss();
                }
            });

            kuaituDialog.setCancelable(false);
            kuaituDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_Location_Service) {
            initGps();
        }
    }

    private boolean preLockPower = true;//连上蓝牙后，主动查询电量

    /**
     * 蓝牙指令响应回调
     */
    private BluetoothHelper.BluetoothCommandCallback commandCallback = new BluetoothHelper.BluetoothCommandCallback() {

        @Override
        public void onSetReturnMode(boolean isSuccessful) {
            if (isSuccessful) {
                progressBarBikeInUse.setVisibility(View.GONE);
                handler.sendEmptyMessage(3);  //dismiss progress
                dropOffBTBike(power + "", btMac, "0");
            } else {  //设置还车模式失败
                progressBarBikeInUse.setVisibility(View.GONE);
                handler.sendEmptyMessage(3);  //dismiss progress
                dropOffBTBike(power + "", btMac, "0");
            }
        }

        @Override
        public void onGetToken(byte[] btToken) {
            MyApplication.btToken = btToken;
            progressBarBikeInUse.setVisibility(View.GONE);
            //获取锁状态（开/关）,如果操作类型为0（用户点击还车），则开启还车流程，
            // 如果操作类型不是0（用户断开蓝牙，后又打开蓝牙）app主动发起连接，后续不会向锁发命令）
            if (caozuo == 0) {
                caozuo = -1;
                BluetoothHelper.getInstance().checkStatus();
            } else {
                handler.sendEmptyMessage(3);  //dismiss progress
                preLockPower = true;
                BluetoothHelper.getInstance().checkDianLiang();
            }
        }

        @Override
        public void onOpenLock(boolean isSuccessful) {

        }

        @Override
        public void onCloseLock(boolean isSuccessful) {
            progressBarBikeInUse.setVisibility(View.GONE);
            if (curPosition.latitude != 0 && curPosition.longitude != 0) {
                closeLockSendLocation();
            }
        }

        @Override
        public void onResetLock(boolean isSuccessful) {

        }

        @Override
        public void onGetLockPower(byte power) {
            BikeInUseActivity.this.power = power;
            if (!preLockPower) {
                if (lockType == 4) {  //不可充电的锁，设置还车模式
                    BluetoothHelper.getInstance().setReturnStatus();
                } else {   //其他蓝牙锁，不设置还车模式，直接还车
                    progressBarBikeInUse.setVisibility(View.GONE);
                    handler.sendEmptyMessage(3);  //dismiss progress
                    dropOffBTBike(power + "", btMac, "0");
                }
            }
        }

        @Override
        public void onCheckLockStatus(boolean isOpen) {
            if (isOpen) {
                progressBarBikeInUse.setVisibility(View.GONE);
                handler.sendEmptyMessage(3);  //dismiss progress
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("请您关闭车锁后再点“还车”进行结算");
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setCancelable(false);
                kuaituDialog.show();
            } else {
                //查询电量
                preLockPower = false;
                BluetoothHelper.getInstance().checkDianLiang();
            }
        }
    };


    //关锁后提交位置信息
    private void closeLockSendLocation() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).closeLockSendLocation(MyApplication.getInstance().getRequestFieldMap(), bikeId, bikeLicense,
                curPosition.longitude + "", curPosition.latitude + "", orderId).enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                SharedPreferencesUtils.getInstance(mContext).putBooleanValue(Constants.LOCK_IS_CLOSE, true);
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }
}
